import time
from datetime import datetime
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from comment.excle_write import excel_append2
from compements.assemblies.check_sf_date import check_sf_date
from selenium.webdriver.support import expected_conditions as EC
from openpyxl import load_workbook
from openpyxl.comments import Comment
def quarterly_statistics(driver, sfzh, mz_time, skip, record,date_1,name):
    driver.switch_to.default_content()
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, "//dt[contains(text(),'随访服务')]"))).click()
    time.sleep(1)
    sf_time = check_sf_date(driver, skip, record)
    print("现有随访记录:", sf_time)

    # 初始化每个季度的计数器
    q1_count = 0  # 第一季度
    q2_count = 0  # 第二季度
    q3_count = 0  # 第三季度
    q4_count = 0  # 第四季度

    # 计算日期间隔的新代码
    interval_days = []  # 存储间隔天数的列表
    # 将字符串日期转换为datetime对象并排序
    if len(sf_time) >= 2:
        date_objects = sorted([datetime.strptime(date_str, "%Y-%m-%d") for date_str in sf_time])
        # 计算相邻日期的间隔
        for i in range(1, len(date_objects)):
            delta = date_objects[i] - date_objects[i - 1]
            interval_days.append(delta.days)
    else:
        interval_days = ["不足两次随访"]  # 不足两次随访时显示提示信息

    # 遍历日期列表
    for date_str in sf_time:
        # 提取月份信息
        month = int(date_str[5:7].replace("-", ""))
        # 判断所属季度并计数
        if 1 <= month <= 3:
            q1_count += 1
        elif 4 <= month <= 6:
            q2_count += 1
        elif 7 <= month <= 9:
            q3_count += 1
        elif 10 <= month <= 12:
            q4_count += 1

    # 输出每个季度的次数
    print(f"第一季度出现的日期次数: {q1_count} 次")
    print(f"第二季度出现的日期次数: {q2_count} 次")
    print(f"第三季度出现的日期次数: {q3_count} 次")
    print(f"第四季度出现的日期次数: {q4_count} 次")
    print(f"随访间隔天数: {interval_days}")

    sf_time = f"已经建立随访的日期-{sf_time}"
    mz_time = f"符合条件的门诊日期-{mz_time}"
    # 将间隔天数列表转换为字符串
    interval_str = ", ".join(map(str, interval_days))

    # 转换评估结果为 Excel 中的表头和内容格式
    column_headers = [
        "身份证号",
        "一季度随访次数", "二季度随访次数", "三季度随访次数", "四季度随访次数",
        "随访日期",
        "随访间隔天数",  # 新增列
        "符合条件的门诊日期",
        "姓名"
    ]

    # 将数据填充到内容列表中
    contents = [
        sfzh,
        q1_count, q2_count, q3_count, q4_count,
        sf_time,
        interval_str,  # 新增间隔天数
        mz_time,
        name
    ]

    # 使用示例
    file_path = "执行结果/慢病随访季度统计结果.xlsx"
    excel_append2(file_path, column_headers, contents)
    if date_1:
        wb = load_workbook(file_path)
        form = {}
        for date in date_1:
            comment_text = ''
            sfsj = date.get("随访时间")
            sffs = date.get("随访方式")
            sfr = date.get("随访人")
            if sfsj in mz_time and sfr == record["签约医生"]:
                comment_text = comment_text+sfsj+"为家医随访"
            elif sfsj in mz_time and sfr != record["签约医生"]:
                comment_text = comment_text + sfsj + "为普通门诊随访"
            elif sfsj not in mz_time and sffs=="电话":
                comment_text = comment_text + sfsj + "为电话随访"
            elif sfsj not in mz_time and sffs=="门诊":
                comment_text = comment_text + sfsj + "为不规范随访"
            form[sfsj] = comment_text
        ws= wb.active
        for row in ws.iter_rows():
            if row[0].value == str(sfzh):
                for key,value in form.items():
                    if "01-01"<=key[5:]<="03-31":
                        index = row[0].row
                        row_c = ws[f"B{index}"]
                        if row_c.comment:
                            text = row_c.comment.text
                            value = value+","+text
                        row_c.comment = Comment(
                            value, ''
                        )
                    elif "04-01"<=key[5:]<="06-30":
                        index = row[0].row
                        row_c = ws[f"C{index}"]
                        if row_c.comment:
                            text = row_c.comment.text
                            value = value+","+text
                        row_c.comment = Comment(
                            value, ''
                        )
                    elif "07-01"<=key[5:]<="09-30":
                        index = row[0].row
                        row_c = ws[f"D{index}"]
                        if row_c.comment:
                            text = row_c.comment.text
                            value = value+","+text
                        row_c.comment = Comment(
                            value, ''
                        )
                    elif "10-01"<=key[5:]<="12-31":
                        index = row[0].row
                        row_c = ws[f"E{index}"]
                        if row_c.comment:
                            text = row_c.comment.text
                            value = value+","+text
                        row_c.comment = Comment(
                            value, ''
                        )

        wb.save(file_path)